package base.inputandoutput;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;
import java.nio.charset.StandardCharsets;

public class PushbackInputStreamDemo {

    private static final String s = "abcdefg";

    public static void main(String[] args) {
        unReadBytes();
    }

    private static void unReadOne() {
        try(
            ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
            PushbackInputStream pis = new PushbackInputStream(bis);
        ) {
            int n;
            while ((n = pis.read()) != -1) {
                System.out.println((char) n);
                if ('b' == (char)n) {
                    // 回推一个字节
                    pis.unread('B');
                }
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    private static void unReadBuffer() {
        try(
            ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
            PushbackInputStream pis = new PushbackInputStream(bis, 4);
        ) {
            int n;
            byte[] buffer = new byte[4];
            while ((n = pis.read(buffer)) != -1) {
                System.out.println(new String(buffer));
                if("abcd".equals(new String(buffer))) {
                    // 回推缓存中的一部分数据
                    pis.unread(buffer,2,2);
                }
                // 清空缓存
                buffer = new byte[4];
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    private static void unReadBytes() {
        try(
            ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
            PushbackInputStream pis = new PushbackInputStream(bis, 3);
        ) {
            int n;
            byte[] buffer = new byte[3];
            while ((n = pis.read(buffer)) != -1) {
                System.out.println(new String(buffer));
                if("abc".equals(new String(buffer))) {
                    // 回推缓存中的一部分数据
                    pis.unread(new byte[]{'A', 'B', 'C'});
                }
                // 清空缓存
                buffer = new byte[3];
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
